package helpers;

import java.io.BufferedWriter;
import java.io.FileWriter;

/**
 * Singleton
 * Custom logger to fit our purposes.
 * It supports: 
 * 	- Logging to a standard file
 *  - Logging on console (just using system out) 
 * It depends on: 
 *  - Configuration file. If logging is set to file, it will ouput
 *    to file. If set to stdout, it will print on console. If 
 *    disabled, do nothing.
 *    
 * The format of the logs is a unix timestamp, with the log message appended
 * 
 * [unixtimestamp] : MESSAGE GOES HERE
 * 
 * @author psyomn
 */
public class CustomLogger {
	
	private static final String mStandardLogFileName = new String("standard.log");
	private static final String mLogTypeLabel_stdout = new String("stdout");
	private static final String mLogTypeLabel_file = new String("file");
	private static CustomLogger mInst = null; 
	
	private CustomLogger(){}
	
	/**
	 * @return the instance  
	 */
	public synchronized static CustomLogger getInst()
	{
		/** TODO add configuration setup here */
		if (null == mInst)
		{
			mInst = new CustomLogger(); 
		}
		
		return mInst; 
	}
	
	/**
	 * This logs a debug message to the standard 
	 * log file. It calls the other function with the 
	 * standard log file name.
	 * @param message
	 */
	public synchronized void log(String iMessage)
	{
		log(iMessage, mStandardLogFileName);
	}
	
	/**
	 * This writes to a log file with a specific name.
	 * @param iMessage
	 * @param iFilename
	 */
	public synchronized void log(String iMessage, String iFilename)
	{
		String typeOfLogging = Configuration.inst().getAttribute("logfile");
		String logHead = (System.currentTimeMillis()/1000) + ": "; 
		FileWriter fw; 
		BufferedWriter bw; 
		
		if (typeOfLogging.equals(mLogTypeLabel_stdout))
		{
			System.out.println(logHead + iMessage);
		}
		
		else if (typeOfLogging.equals(mLogTypeLabel_file))
		{
			try 
			{
				fw = new FileWriter(iFilename, true); // true so that we append
				bw = new BufferedWriter(fw);
				
				bw.write(logHead + iMessage + "\n");
				bw.close();
			}
			
			catch(Exception e)
			{
				e.printStackTrace();
			}
		}
		
		else
		{
			// Don't move, do nothing, stay silent. They might not see you. 
		}
	}
	
	
}
